package com.gtm.service;

import com.gtm.model.Pager;
import com.gtm.model.Topic;
import com.gtm.model.User;
import com.mongodb.BasicDBObject;
import com.mongodb.gridfs.GridFSDBFile;
import com.mongodb.gridfs.GridFSFile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.config.ResourceNotFoundException;
import org.springframework.core.io.Resource;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.gridfs.GridFsOperations;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

/**
 * Created by 骆清波 on 2017/10/30.
 */
@Service
public class BaseService<T>{
    @Autowired
    GridFsOperations fs;
    public GridFSDBFile getFile(String resourceId) {
        GridFSDBFile mongoFile = fs.findOne(new Query(Criteria.where("_id").is(resourceId)));
        if (mongoFile == null)
            throw new RuntimeException();
        return mongoFile;
    }

    public String upUserFile(MultipartFile file, T t) throws IOException {
        BasicDBObject dbObj=createDBObject(t);
        GridFSFile reDBObj = fs.store(file.getInputStream(), file.getOriginalFilename(), file.getContentType(),
                dbObj);
        return reDBObj.getId().toString();
    }

    public BasicDBObject createDBObject(T t) {
        BasicDBObject dbObj = new BasicDBObject("className", t.getClass().getName());
        return dbObj;
    }

    public Pager<T> listToPage(List<T> list, PageRequest pageRequest) {
        System.out.println(2);
        System.out.println(list.toString());
        int size=pageRequest.getPageSize();
        int page=pageRequest.getPageNumber();
        int total=list.size();
        int pageCount=(total+size-1)/size;

        pageCount-=1;
        if (page>pageCount){
            page=pageCount;
        }
        int start=(page)*size;
        int end=start+size;
        if (end>=total){
            end=total;
        }
        if(list.size()==0){
            PageImpl<T> page1=new PageImpl(list);
            Pager<T> pager =new Pager<T>();
            pager.setObjs(page1);
            pager.setCount(total);
            pager.setSize(size);
            return pager;
        }
        PageImpl<T> page1=new PageImpl(list.subList(start,end));
        Pager<T> pager =new Pager<T>();
        pager.setObjs(page1);
        pager.setCount(total);
        pager.setSize(size);
        return pager;
    }


}
